package com.mrstage.ndkplayer;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.widget.TextView;
import android.widget.Toast;

import com.huantansheng.easyphotos.EasyPhotos;
import com.mrstage.ndkplayer.databinding.ActivityMainBinding;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {


    private ActivityMainBinding binding;
    private NDKPlayer mNdkPlayer;
    private List<String> mVideoPaths = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        getVideo();
        mNdkPlayer = new NDKPlayer();

//        Toast.makeText(MainActivity.this, dataSource, Toast.LENGTH_SHORT).show();

        mNdkPlayer.setDataSource(mVideoPaths.get(0));

        mNdkPlayer.setOnPreparedListener(() -> {
            runOnUiThread(() -> {
                Toast.makeText(MainActivity.this, "准备播放", Toast.LENGTH_SHORT).show();
            });
            mNdkPlayer.start();
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        mNdkPlayer.prepare();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mNdkPlayer.stop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mNdkPlayer.release();
    }

    private void getVideo() {
        ContentResolver contentResolver = getContentResolver();
        Uri targetUrl = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
        Cursor cursor = contentResolver.query(targetUrl, null,
                MediaStore.Video.Media.MIME_TYPE + "=? or "
                        + MediaStore.Video.Media.MIME_TYPE + "=?",
                new String[] { "video/mp4", "video/avi" },
                MediaStore.Video.Media.DEFAULT_SORT_ORDER);
        while (cursor.moveToNext()) {
            String path = cursor.getString(cursor
                    .getColumnIndex(MediaStore.Video.Media.DATA));
            mVideoPaths.add(path);
        }
        cursor.close();
        System.out.println("Video = " + mVideoPaths.toString());
    }
}